package me.maiz.tool.codemonitor.controller;

import lombok.extern.slf4j.Slf4j;
import me.maiz.tool.codemonitor.common.LayUIResult;
import me.maiz.tool.codemonitor.dal.StudentRepo;
import me.maiz.tool.codemonitor.entity.Student;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("data")
@Slf4j
public class GroupController {

    @Autowired
    private StudentRepo studentRepo;

    @RequestMapping("students")
    public LayUIResult<Student> students() {
        LayUIResult<Student> result = new LayUIResult<>();
        try {
            List<Student> all = studentRepo.findAll();
            result.setCode(0);
            result.setCount(all.size());
            result.setData(all);
        } catch (Exception e) {
            log.info("查询出错", e);
            result.setCode(-1);
            result.setMsg("查询出错" + e.getMessage());
        }
        return result;
    }


    @RequestMapping("upload")
    public LayUIResult upload(MultipartFile file) {
        try {
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            int i=0;
            for (Row row : sheet) {
                i++;
                if(i==1){
                    continue;
                }
                String realname = row.getCell(0).getStringCellValue();
                String email = row.getCell(1).getStringCellValue();
                String username = row.getCell(2).getStringCellValue();
                Student student = null;
                log.info("realname:{}",realname);
                if(realname!=null){
                    Student exist = studentRepo.findByName(realname);
                    if(exist !=null){
                        student=exist;
                    }else{
                        student=new Student();
                    }
                }
                student.setName(realname);
                student.setEmail(email);
                student.setGiteeUsername(username);
                studentRepo.save(student);

            }

        } catch (IOException e) {
            log.warn("上传文件失败",e);
            return LayUIResult.fail("上传文件失败:"+e.getMessage());
        }
        return LayUIResult.success();
    }

}
